package org.zhaozhen.pay.controller;


import com.alipay.api.internal.util.AlipaySignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.zhaozhen.order.domain.AdoptOrder;
import org.zhaozhen.order.service.IAdoptOrderService;
import org.zhaozhen.pay.config.AlipayConfig;
import org.zhaozhen.pay.constants.AlipayConstant;
import org.zhaozhen.pay.domain.AlipayInfo;
import org.zhaozhen.pay.domain.PayBill;
import org.zhaozhen.pay.service.IAlipayInfoService;
import org.zhaozhen.pay.service.IPayBillService;
import org.zhaozhen.quartz.constant.JobTypeConstants;
import org.zhaozhen.quartz.service.IQuartzService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class AlipayController {
    @Autowired
    private IPayBillService payBillService;
    @Autowired
    private IAlipayInfoService alipayInfoService;
    @Autowired
    private IAdoptOrderService adoptOrderService;
    @Autowired
    private IQuartzService quartzService;

    @PostMapping("/notify")
    public void notify(HttpServletRequest request){
        try {
            //获取支付宝POST过来反馈信息
            Map<String,String> params = new HashMap<String,String>();
            Map<String,String[]> requestParams = request.getParameterMap();
            for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
                String name = (String) iter.next();
                String[] values = (String[]) requestParams.get(name);
                String valueStr = "";
                for (int i = 0; i < values.length; i++) {
                    valueStr = (i == values.length - 1) ? valueStr + values[i]
                            : valueStr + values[i] + ",";
                }
                params.put(name, valueStr);
            }
            String unionPaySn  = params.get("out_trade_no");
            System.out.println("-------------------"+unionPaySn);
            PayBill payBill = payBillService.queryByUnionPaySn(unionPaySn);
            if (payBill!=null) {
                AlipayInfo alipayInfo = alipayInfoService.getByShopId(payBill.getShop_id());
                System.out.println("11111111111");
                boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayInfo.getAlipay_public_key(), AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名


                if (signVerified) {//验证成功
                    //商户订单号
                    String out_trade_no = request.getParameter("out_trade_no");
                    System.out.println("22222222222222222222");
                    //支付宝交易号
                    String trade_no = request.getParameter("trade_no");

                    //交易状态
                    String trade_status = request.getParameter("trade_status");

                    if (trade_status.equals("TRADE_FINISHED")) {
                        //判断该笔订单是否在商户网站中已经做过处理
                        //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                        //如果有做过处理，不执行商户的业务程序
                        System.out.println("3333333333333");
                        //注意：
                        //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                    } else if (trade_status.equals("TRADE_SUCCESS")) {
                        payBill.setState(1);
                        System.out.println("-----------------------------------------");
                        payBill.setUpdateTime(new Date());
                        payBillService.update(payBill);
                        //2.记录支付流水
                        //3.查询对应的业务订单，并修改订单状态
                        String jobName = "";
                        if(AlipayConstant.BUSINESS_TYPE_ADOPT.equals(payBill.getBusinessType())){
                            System.out.println("==========================================");
                            AdoptOrder adoptOrder = adoptOrderService.queryById(payBill.getBusinessKey());
                            adoptOrder.setState(1);//待发货
                            adoptOrderService.update(adoptOrder);
                            //干掉定时器
                            jobName = JobTypeConstants.TIME_OUT_ADOPT_LAST_PAY + adoptOrder.getId();
                        }
                        quartzService.removeJob(jobName);
                    }
                } else {//验证失败

                    //调试用，写文本函数记录程序运行情况是否正常
                    //String sWord = AlipaySignature.getSignCheckContentV1(params);
                    //AlipayConfig.logResult(sWord);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
